import { useState, useEffect } from "react";
import { Button, Modal, Form, Input, DatePicker, message, Select } from "antd";
import Navigate from "../components/Navigate";
import "./AdminPromotions.css";
import { 
  getPromotionList,
  publishPromotion,
  editPromotion,
  deletePromotion,
  togglePromotionStatus
} from '../api/AdminPromotionApi';
import moment from 'moment';

const { Option } = Select;

function AdminPromotions() {
  const [promotions, setPromotions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [form] = Form.useForm();
  const [editingItem, setEditingItem] = useState(null);
  const [current, setCurrent] = useState(1);
  const [size, setSize] = useState(10);
  const [total, setTotal] = useState(0);
  // 加载促销活动数据
  const loadPromotions = async () => {
    setLoading(true);
    try {
      const response = await getPromotionList(current, size);
      if (response.success && Array.isArray(response.data.records)) {
        setPromotions(response.data.records);
        
      } else {
        message.error('获取促销活动列表失败');
      }
    } catch (error) {
      message.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadPromotions();
  }, [current, size]);

  // 处理发布新活动
  const handlePublish = async (values) => {
    try {
      const promotionData = {
        id: editingItem ? editingItem.id : undefined, // Include ID for editing
        type: values.type, // 从表单中获取活动类型
        title: values.title,
        description: values.content, // Assuming content is the description
        startTime: values.timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
        endTime: values.timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
        isActive: editingItem ? editingItem.isActive : 1, // 保持原有状态或默认启用
      };
  
      if (editingItem) {
        // 编辑现有活动
        await editPromotion(promotionData); // Pass the entire promotionData
        message.success('编辑成功');
      } else {
        // 发布新活动
        await publishPromotion(promotionData);
        message.success('发布成功');
      }
      
      setShowModal(false);
      form.resetFields();
      setEditingItem(null);
      loadPromotions();
    } catch (error) {
      message.error(editingItem ? '编辑失败' : '发布失败');
    }
  };

    // 添加handleEdit函数
    const handleEdit = (item) => {
      setEditingItem(item);
      form.setFieldsValue({
        title: item.title,
        type: item.type,
        content: item.description,
        timeRange: [
          moment(item.startTime),
          moment(item.endTime),
        ],
        isActive: item.isActive,
      });
      setShowModal(true);
    };

  // 处理删除
  const handleDelete = (item) => {
    // 使用 window.confirm 进行简单的确认
    const confirmed = window.confirm(`确定要删除"${item.title}"这个活动吗？`);
    if (confirmed) {
      // 用户确认删除
      deletePromotion(item.id)
        .then(() => {
          message.success('删除成功'); // 显示成功消息
          loadPromotions(); // 重新加载促销活动列表
        })
        .catch(() => {
          message.error('删除失败'); // 显示错误消息
        });
    }
  };

  // 修改 Modal 的标题
  const modalTitle = editingItem ? '编辑活动' : '发布新活动';

  // Function to handle closing the modal
  const handleModalClose = () => {
    setShowModal(false);
    form.resetFields(); // Optionally reset the form fields
    setEditingItem(null); // Reset the editing item
  };

  // Function to handle enabling/disabling a promotion
  const handleToggleActive = async (item) => {
    const newStatus = item.isActive === 1 ? 0 : 1; // Toggle between active and inactive
    try {
      await togglePromotionStatus(item.id, newStatus); // 调用新的 API 接口
      message.success(newStatus === 1 ? '启用成功' : '禁用成功');
      loadPromotions(); // Reload promotions to reflect changes
    } catch (error) {
      message.error('操作失败');
    }
  };

  // Function to handle viewing details
  const handleViewDetails = (item) => {
    // Implement the logic to show details, e.g., open a modal with more information
    Modal.info({
      title: item.title,
      content: (
        <div>
          <p>{item.description}</p>
          <p>开始时间: {item.startTime}</p>
          <p>结束时间: {item.endTime}</p>
          <p>状态: {getStatusText(item)}</p>
        </div>
      ),
      onOk() {},
    });
  };

  return (
    <div className="admin-layout">
      <Navigate activeItem="促销活动管理" />

      <div className="main-content">
        <div className="promotion-container">
          {/* 头部 */}
          <div className="header">
            <h2>促销活动管理</h2>
            <Button 
              type="primary"
              onClick={() => setShowModal(true)}
              style={{ 
                backgroundColor: '#ff6699',
                borderColor: '#ff6699'
              }}
            >
              发布新活动
            </Button>
          </div>

          {/* 活动列表 */}
          <div className="table-container">
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>活动标题</th>
                  <th>开始时间</th>
                  <th>结束时间</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {promotions.map((item) => (
                  <tr key={item.id}>
                    <td>{item.id}</td>
                    <td>{item.title}</td>
                    <td>{item.startTime}</td>
                    <td>{item.endTime}</td>
                    <td>
                      <span className={`status-badge ${getStatusClass(item)}`}>
                        {getStatusText(item)}
                      </span>
                    </td>
                    <td>
                      {/* <Button type="link" onClick={() => handleEdit(item)}>
                        编辑
                      </Button> */}
                      <Button type="link" danger onClick={() => handleDelete(item)}>
                        删除
                      </Button>
                      <Button 
                        type="link" 
                        onClick={() => handleToggleActive(item)}
                      >
                        {item.isActive === 1 ? '禁用' : '启用'}
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* 发布新活动弹窗 */}
          <Modal
            title={modalTitle}
            open={showModal}
            onCancel={handleModalClose}
            footer={null}
          >
            <Form
              form={form}
              onFinish={handlePublish}
              layout="vertical"
            >
              <Form.Item
                name="type"
                label="活动类型"
                rules={[{ required: true, message: '请选择活动类型' }]}
              >
                <Select placeholder="请选择活动类型">
                  <Option value="normal">普通</Option>
                  <Option value="free">免费</Option>
                  <Option value="half_price">半价</Option>
                  <Option value="double_upload">双倍上传</Option>
                  <Option value="double_download">双倍下载</Option>
                  <Option value="double_upload_download">双倍上传下载</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="title"
                label="活动标题"
                rules={[{ required: true, message: '请输入活动标题' }]}
              >
                <Input placeholder="请输入活动标题" />
              </Form.Item>
              <Form.Item
                name="content"
                label="活动内容"
                rules={[{ required: true, message: '请输入活动内容' }]}
              >
                <Input.TextArea rows={4} placeholder="请输入活动内容" />
              </Form.Item>
              <Form.Item
                name="timeRange"
                label="活动时间"
                rules={[{ required: true, message: '请选择活动时间' }]}
              >
                <DatePicker.RangePicker 
                  showTime 
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" block>
                  {editingItem ? '保存' : '发布'}
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </div>
    </div>
  );
}

// 工具函数
const getStatusClass = (item) => {
  const now = new Date();
  const start = new Date(item.startTime);
  const end = new Date(item.endTime);
  
  if (now < start) return 'status-pending';
  if (now > end) return 'status-expired';
  return 'status-active';
};

const getStatusText = (item) => {
  const now = new Date();
  const start = new Date(item.startTime);
  const end = new Date(item.endTime);
  
  if (now < start) return '未开始';
  if (now > end) return '已结束';
  return '进行中';
};

export default AdminPromotions;